﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.OleDb;

/// <summary>
/// 操作数据库的一些公用函数
/// </summary>
public class DB
{
    public static string con_str = ConfigurationManager.ConnectionStrings["access_con"].ConnectionString
        + HttpContext.Current.Server.MapPath(ConfigurationManager.ConnectionStrings["access_path"].ConnectionString);

    public DB() 
    {
    }
    //获取连接
	public static OleDbConnection  conn()
	{
        OleDbConnection conn = new OleDbConnection(con_str);
        return conn;
	}
    //根据语句获取对象
    public static Object getObject(string sql)
    {
        OleDbConnection conn = DB.conn();
        OleDbCommand comm = new OleDbCommand();
        try
        {
            if (conn != null)
            {
                conn.Open();
                comm.Connection = conn;
                comm.CommandText = sql;
                return comm.ExecuteScalar();
            }
        }
        catch (Exception error)
        {
            return null;
        }
        finally {
            if (comm != null) comm.Dispose();
            conn.Close();
        }
        return null;
    }
    //执行查询并返回DataTable
    public static DataTable getDataTable(string sql) {

        OleDbConnection conn = DB.conn();
        OleDbCommand comm = new OleDbCommand();
        try
        {
            if (conn != null)
            {
                conn.Open();
                comm.Connection = conn;
                comm.CommandText = sql;
                OleDbDataAdapter da = new OleDbDataAdapter();
                da.SelectCommand = comm ;
                DataTable dt = new DataTable();
                da.Fill(dt);
                return dt;
            }
        }
        catch (Exception error)
        {
            return null;
        }
        finally
        {
            if (comm != null) comm.Dispose();
            conn.Close();
        }
        return null;
    }

    //执行无查询语句
    public static bool doNonQuery(string sql)
    {

        OleDbConnection conn = DB.conn();
        OleDbCommand comm = new OleDbCommand();
        try
        {
            if (conn != null)
            {
                conn.Open();
                comm.Connection = conn;
                comm.CommandText = sql;
                comm.ExecuteNonQuery();
                return true;
            }
        }
        finally
        {
            if (comm != null) comm.Dispose();
            conn.Close();
        }
        return false;
    }
    public static void bindData(String sql, Repeater repeater)
    {
        DataTable dt = DB.getDataTable(sql);
        repeater.DataSource = dt;
        repeater.DataBind();
    }
}
